package org.study.shardingsphere.ds.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年09月10日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/ds")
public class DataSourceInfoController {
    private final DataSource dataSource;

    @GetMapping("/list")
    public Object listDataSourceInfo() {
        // dynamic-datasource中的数据源信息
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
        Map<String, DataSource> dataSourceMap = dynamicRoutingDataSource.getDataSources();
        return JSONUtil.toJsonStr(dataSourceMap);
    }

    @GetMapping("/exists/{dsKey}")
    public Boolean existsDataSource(@PathVariable("dsKey") String dsKey) {
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
        /*DataSource existsDataSource = dynamicRoutingDataSource.getDataSource(dsKey);
        return existsDataSource != null;*/
        return dynamicRoutingDataSource.getDataSources().containsKey(dsKey);
    }

    @GetMapping("/check/{dsKey}")
    public Boolean checkDataSource(@PathVariable("dsKey") String dsKey) {
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
        DataSource existsDataSource = dynamicRoutingDataSource.getDataSource(dsKey);
        if (existsDataSource != null) {
            try (Connection connection = existsDataSource.getConnection();
                 Statement statement = connection.createStatement()) {
                statement.execute("SELECT 1");
                return Boolean.TRUE;
            } catch (SQLException e) {
            }
        }
        return Boolean.FALSE;
    }
}
